package cn.edu.jssvc.bluecar.asr;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.huawei.hiai.asr.AsrConstants;
import com.huawei.hiai.asr.AsrRecognizer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.jssvc.bluecar.MainActivity;


public class AsrInit {

    private static final String TAG = "MainActivity";

    private AsrRecognizer mAsrRecognizer;

    private Handler handler;

    private MyAsrListener mMyAsrListener = new MyAsrListener();
    private Context context;

    public AsrInit(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
        mMyAsrListener.setHandler(handler);
        mMyAsrListener.setAsrInit(this);
        mMyAsrListener.setContext(context);
    }

    public void init() {
        // 创建AsrRecognizer实例
        mAsrRecognizer = AsrRecognizer.createAsrRecognizer(context);

        if (isSupportAsr(context)) {
            initEngine(AsrConstants.ASR_SRC_TYPE_RECORD);
        } else {
            Log.e(TAG, "not support asr!");
        }

    }

    private boolean isSupportAsr(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo("com.huawei.hiai", 0);
            Log.d(TAG, "Engine versionName: " + packageInfo.versionName + " ,versionCode: " + packageInfo.versionCode);
            // 最开始支持asr功能的hiai引擎版本，小于此版本不支持asr功能
            if (packageInfo.versionCode <= 801000300) {
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d(TAG, "not support asr");
            return false;
        }
        return true;
    }

    /**
     * 初始化引擎
     *
     * @param srcType 数据源类型
     */
    private void initEngine(int srcType) {
        Log.d(TAG, "initEngine() srcType" + srcType);
        Intent initIntent = new Intent();
        initIntent.putExtra(AsrConstants.ASR_AUDIO_SRC_TYPE, srcType);
        initIntent.putExtra(AsrConstants.ASR_VAD_END_WAIT_MS, 2000); // 设置前置vad时间
        initIntent.putExtra(AsrConstants.ASR_VAD_FRONT_WAIT_MS, 4000); // 设置后置vad时间
        if (mAsrRecognizer != null) {
            mAsrRecognizer.init(initIntent, mMyAsrListener);
        }
    }

    public void startRecord() {
        Log.d(TAG, "startRecord() ");
//        showResult.setText("识别中：");
//        mHandler.sendEmptyMessage(DELAYED_START_RECORD);
        setBtEnabled(false);
        startListening(AsrConstants.ASR_SRC_TYPE_RECORD, null);
    }

    /**
     * 调用asr的startListening接口
     *
     * @param srcType  数据源类型
     * @param filePath 如果识别的是音频文件，传入音频文件路径
     */
    private void startListening(int srcType, String filePath) {
        Log.d(TAG, "startListening() " + "src_type:" + srcType);
        Intent intent = new Intent();
        intent.putExtra(AsrConstants.ASR_VAD_END_WAIT_MS, 2000);
        intent.putExtra(AsrConstants.ASR_VAD_FRONT_WAIT_MS, 4000);
        intent.putExtra(AsrConstants.ASR_TIMEOUT_THRESHOLD_MS, 20000);
        if (srcType == AsrConstants.ASR_SRC_TYPE_FILE) {
            intent.putExtra(AsrConstants.ASR_SRC_FILE, filePath);
        }
        if (mAsrRecognizer != null) {
            mAsrRecognizer.startListening(intent);
        }
    }


    /**
     * 停止识别，调用此接口会有onResult回调返回识别结果
     */
    protected void stopListening() {
        Log.d(TAG, "stopListening() ");
        if (mAsrRecognizer != null) {
            mAsrRecognizer.stopListening();  //停止识别
        }

        if (MainActivity.bluetoothUtils.isConnected()) {
            MainActivity.bluetoothUtils.write("ONF");
        }

    }

    /**
     * 取消识别，调用此接口不会有onResult返回结果
     */
    public void cancelListening() {
        Log.d(TAG, "cancelListening() ");
        setBtEnabled(true);
        if (mAsrRecognizer != null) {
            mAsrRecognizer.cancel();  //取消识别
        }
        if (MainActivity.bluetoothUtils.isConnected()) {
            MainActivity.bluetoothUtils.write("ONF");
        }
    }

    public void destroyEngine() {
        Log.d(TAG, "destroyEngine() ");
        if (mAsrRecognizer != null) {
            mAsrRecognizer.destroy();  //引擎释放
        }
        mAsrRecognizer = null;
    }


    String getOnResult(Bundle partialResults, String key) {
        String json = partialResults.getString(key);
        final StringBuilder sb = new StringBuilder();
        try {
            JSONObject result = new JSONObject(json);
            JSONArray items = result.getJSONArray("result");
            for (int i = 0; i < items.length(); i++) {
                String word = items.getJSONObject(i).getString("word");
                double confidences = items.getJSONObject(i).getDouble("confidence");
                sb.append(word);
//                showResults.setText(word);
            }
            String ssb = sb.toString();
            Log.e(TAG, "getOnResult: " + ssb);
//            showResults.setText(ssb);

            if (MainActivity.bluetoothUtils.isConnected()) {
                int upIndex = ssb.lastIndexOf("前");
                int downIndex = ssb.lastIndexOf("后");
                int leftIndex = ssb.lastIndexOf("左");
                int rightIndex = ssb.lastIndexOf("右");
                int stopIndex = ssb.lastIndexOf("停");
                int[] indexes = new int[]{-1, upIndex, downIndex, leftIndex, rightIndex,
                        stopIndex};
                int maxIndex = max(indexes);
                switch (maxIndex) {
                    case 1:
                        MainActivity.bluetoothUtils.write("ONA");
                        break;
                    case 2:
                        MainActivity.bluetoothUtils.write("ONB");
                        break;
                    case 3:
                        MainActivity.bluetoothUtils.write("ONC");
                        break;
                    case 4:
                        MainActivity.bluetoothUtils.write("OND");
                        break;
                    default:
                        MainActivity.bluetoothUtils.write("ONF");
                        break;
                }
            }


        } catch (JSONException exp) {
            Log.e(TAG, "JSONException: " + exp.toString());
        }
        return sb.toString();
    }


    int max(int[] arr) {
        int max = arr[0];
        int index = 0;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
                index = i;
            }
        }
        return index;
    }

    void setBtEnabled(boolean isEnabled) {
//        view.findViewById(R.id.bt_startListen).setEnabled(isEnabled);

        if (isEnabled) {
            this.handler.sendEmptyMessage(MainActivity.BT_ENABLE_TRUE);
            if (MainActivity.bluetoothUtils.isConnected()) {
                MainActivity.bluetoothUtils.write("ONF");
            }
        } else {
            this.handler.sendEmptyMessage(MainActivity.BT_ENABLE_FALSE);
        }

    }
}
